import pygame
import io
import time
import threading
import queue
import os
from openai import OpenAI
from config import SILICONFLOW_API_KEY, TTS_BASE_URL, DEFAULT_MODEL, DEFAULT_VOICE, DEFAULT_RESPONSE_FORMAT


class TTSHanlder:
    def __init__(self):
        self.client = OpenAI(
            api_key=SILICONFLOW_API_KEY,
            base_url=TTS_BASE_URL
        )
        self.default_model = DEFAULT_MODEL
        self.default_voice = DEFAULT_VOICE
        self.default_response_format = DEFAULT_RESPONSE_FORMAT
        pygame.mixer.init()
        # 设置每个段落的最大字符数
        self.max_chars_per_segment = 1000

    def text_to_speech(self, text, model=None, voice=None, response_format=None):
        """
        将文本转换为语音
        
        Args:
            text (str): 要转换的文本
            model (str): 语音模型
            voice (str): 语音
            response_format (str): 音频格式
            
        Returns:
            bytes: 音频数据
        """
        # 使用默认值如果未提供参数
        if model is None:
            model = self.default_model
        if voice is None:
            voice = self.default_voice
        if response_format is None:
            response_format = self.default_response_format
            
        try:
            # 使用OpenAI兼容的API调用TTS服务
            response = self.client.audio.speech.create(
                model=model,
                voice=voice,
                input=text,
                response_format=response_format
            )
            
            # 返回音频数据
            return response.content
        except Exception as e:
            print(f"Error calling TTS API: {e}")
            return None

    def split_text_into_segments(self, text):
        """
        将文本分割成较小的段落
        
        Args:
            text (str): 要分割的文本
            
        Returns:
            list: 文本段落列表
        """
        # 如果文本长度小于最大字符数，直接返回
        if len(text) <= self.max_chars_per_segment:
            return [text]
            
        # 按句子分割文本
        segments = []
        current_segment = ""
        
        # 简单的句子分割（以句号、感叹号、问号为分割点）
        sentences = []
        temp_sentence = ""
        
        for char in text:
            temp_sentence += char
            if char in ['。', '！', '？', '.', '!', '?']:
                sentences.append(temp_sentence)
                temp_sentence = ""
        
        # 如果还有剩余文本（没有以标点符号结尾）
        if temp_sentence:
            sentences.append(temp_sentence)
            
        # 将句子组合成段落
        for sentence in sentences:
            # 如果当前段落加上新句子超过最大字符数，则保存当前段落并开始新段落
            if len(current_segment) + len(sentence) > self.max_chars_per_segment and current_segment:
                segments.append(current_segment)
                current_segment = sentence
            else:
                current_segment += sentence
                
        # 添加最后一个段落
        if current_segment:
            segments.append(current_segment)
            
        return segments

    def convert_and_play_segment(self, segment_text, segment_index, model=None, voice=None, response_format=None, output_dir=None):
        """
        转换并播放单个段落，同时保存为文件
        
        Args:
            segment_text (str): 段落文本
            segment_index (int): 段落索引
            model (str): 语音模型
            voice (str): 语音
            response_format (str): 音频格式
            output_dir (str): 输出目录
            
        Returns:
            tuple: (segment_index, audio_data, file_path)
        """
        print(f"正在转换第 {segment_index+1} 段...")
        audio_data = self.text_to_speech(segment_text, model, voice, response_format)
        
        file_path = None
        if audio_data and output_dir:
            # 保存音频文件
            filename = f"segment_{segment_index+1:03d}.{response_format}"
            file_path = os.path.join(output_dir, filename)
            
            with open(file_path, "wb") as f:
                f.write(audio_data)
                
        return (segment_index, audio_data, file_path)

    def read_text_file(self, file_path):
        """
        读取文本文件并返回内容
        
        Args:
            file_path (str): 文件路径
            
        Returns:
            str: 文件内容
        """
        try:
            with open(file_path, 'r', encoding='utf-8') as file:
                return file.read()
        except Exception as e:
            print(f"Error reading file: {e}")
            return None